<?php

namespace App\Http\Controllers;

use App\Models\File;
use App\Http\Requests\StoreFileRequest;
use App\Http\Requests\UpdateFileRequest;
use App\Http\Resources\FileResource;
use App\Http\Services\FileService;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request, File $file)
    {
        // 文件列表
        $this->authorize('viewAny', $file);
        $data = File::orderBy('created_at', 'DESC')->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        return $this->success('查询成功', FileResource::collection($data));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreFileRequest $request)
    {
        $fileService = new FileService();
        $resultArr = $fileService->uploadFile($request->file('file'), $request->hasFile('file'));
        if ($resultArr["status"]) {
            return $this->success('上传成功', ["url" => $resultArr["message"]]);
        }
        return $this->error($resultArr["message"]);
    }

    /**
     * Display the specified resource.
     */
    public function show(File $file)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(File $file)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateFileRequest $request, File $file)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(File $file)
    {
        $this->authorize('delete', $file);
        // 删除文件
        $filePath = str_replace('{' . env('APP_NAME') . '}/storage/', '/public/', $file->url);
        if (Storage::exists($filePath)) {
            Storage::delete($filePath);
            $file->delete();
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
}
